using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyHomeworkWebAPi.Models.ef;
using MyHomeworkWebAPi.Models.Request;
using MyHomeworkWebAPi.Models.response;
using MyHomeworkWebAPi.Services;

namespace MyHomeworkWebAPi.Controllers
{
    /// <summary>
    /// 互动管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class InteractionsController : ControllerBase
    {
        private readonly IInteractionServices _interactionServices;
        private readonly ILogger<InteractionsController> _logger;

        /// <summary>
        /// 构造函数，注入互动服务和日志服务
        /// </summary>
        /// <param name="interactionServices">互动服务接口</param>
        /// <param name="logger">日志服务</param>
        public InteractionsController(IInteractionServices interactionServices, ILogger<InteractionsController> logger)
        {
            _interactionServices = interactionServices;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有互动记录
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            var interactions = await _interactionServices.GetAllAsync();
            return Ok(ApiResponse<List<Interaction>>.SuccessResponse(interactions));
        }

        /// <summary>
        /// 根据ID获取互动记录
        /// </summary>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(Guid id)
        {
            var interaction = await _interactionServices.GetByIdAsync(id);
            if (interaction == null)
            {
                return NotFound(ApiResponse<Interaction>.ErrorResponse("互动记录不存在", 404));
            }
            return Ok(ApiResponse<Interaction>.SuccessResponse(interaction));
        }

        /// <summary>
        /// 创建互动记录
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] InteractionCreateRequest request)
        {
            try
            {
                var interaction = await _interactionServices.CreateAsync(request);
                _logger.LogInformation($"Interaction created successfully for user {request.UserId} and product {request.ProductId}");
                return Ok(ApiResponse<Interaction>.SuccessResponse(interaction, "互动记录创建成功"));
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Failed to create interaction: {ex.Message}");
                return BadRequest(ApiResponse<Interaction>.ErrorResponse(ex.Message, 400));
            }
        }

        /// <summary>
        /// 删除互动记录
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(Guid id)
        {
            var result = await _interactionServices.DeleteAsync(id);
            if (!result)
            {
                return NotFound(ApiResponse<bool>.ErrorResponse("互动记录不存在", 404));
            }
            return Ok(ApiResponse<bool>.SuccessResponse(true, "互动记录删除成功"));
        }

        /// <summary>
        /// 获取用户的互动记录列表
        /// </summary>
        [HttpGet("user/{userId}")]
        public async Task<IActionResult> GetByUserId(Guid userId)
        {
            var interactions = await _interactionServices.GetByUserIdAsync(userId);
            return Ok(ApiResponse<List<Interaction>>.SuccessResponse(interactions));
        }

        /// <summary>
        /// 获取商品的互动记录列表
        /// </summary>
        [HttpGet("product/{productId}")]
        public async Task<IActionResult> GetByProductId(Guid productId)
        {
            var interactions = await _interactionServices.GetByProductIdAsync(productId);
            return Ok(ApiResponse<List<Interaction>>.SuccessResponse(interactions));
        }

        /// <summary>
        /// 检查用户是否已收藏商品
        /// </summary>
        [HttpGet("check-favorite")]
        public async Task<IActionResult> CheckFavorite([FromQuery] Guid userId, [FromQuery] Guid productId)
        {
            var isFavorited = await _interactionServices.IsProductFavoritedAsync(userId, productId);
            return Ok(ApiResponse<bool>.SuccessResponse(isFavorited));
        }

        /// <summary>
        /// 获取互动统计数据
        /// </summary>
        [HttpGet("statistics")]
        public async Task<IActionResult> GetStatistics()
        {
            try
            {
                var statistics = await _interactionServices.GetStatisticsAsync();
                return Ok(ApiResponse<InteractionStatistics>.SuccessResponse(statistics));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to get interaction statistics: {ex.Message}");
                return BadRequest(ApiResponse<object>.ErrorResponse(ex.Message, 400));
            }
        }
    }
} 